//
//  ContentView.swift
//  School
//
//  Created by qh w on 2021/5/3.
//

import SwiftUI

struct ContentView: View {
    @StateObject var UserData: CoreData
    @EnvironmentObject var ClassName: ClassNameData
    @Environment(\.colorScheme) var _Color: ColorScheme
    @State var timer = Timer.TimerPublisher(interval: 5, runLoop: .current,
                                            mode: .default).autoconnect()
    @State var errorStr = ""
    @State var showError = false
    @Binding var showWarning: Bool
    @State var isLoaded = false
    @State var allowUpdate = true
    @State var once = false
    @State var UIAController = UIAlertController()
    @Environment(\.presentationMode) var presentation
    var body: some View {
        DispatchQueue.main.async {
            if !once {
                connect()
                once = true
            }
        }
        if !UserData.FILE_DOWNLOAD_ISNOT_FINISHED_FLAG
        {
            DispatchQueue.main.async {
                isLoaded = true
            }
        }
        return ZStack {
            NavigationView {
                ZStack {
                    VStack {
                        LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible())], spacing: 2) {
                            if isLoaded {
                                NavigationLink(destination: ClassSettingView().environmentObject(UserData)) {
                                    Fluent_Rect {
                                        HStack {
                                            VStack(alignment: .leading) {
                                                Image(systemName: "plus.circle.fill")
                                                    .imageScale(.large)
                                                    .padding(.bottom, 10)
                                                Text("添加课程类型")
                                                    .font(.headline)
                                            }
                                            .foregroundColor(.white)
                                            Spacer()
                                        }
                                        .padding(.leading)
                                    }
                                }
                                .frame(height: 120)
                                .padding(.leading)
                                NavigationLink(destination: CalenderEditingView(allowUpdate: self.$allowUpdate).environmentObject(UserData)) {
                                    Fluent_Rect {
                                        HStack {
                                            VStack(alignment: .leading) {
                                                Image(systemName: "square.and.pencil")
                                                    .imageScale(.large)
                                                    .padding(.bottom, 10)
                                                Text("创建修改课表")
                                                    .font(.headline)
                                            }
                                            .foregroundColor(.white)
                                            Spacer()
                                        }
                                        .padding(.leading)
                                    }
                                }
                                .frame(height: 120)
                                .padding(.trailing)
                                NavigationLink(destination: VStack {
                                    SettingsView(showInitButton: true)
                                        .environmentObject(UserData)
                                }) {
                                    Fluent_Rect {
                                        HStack {
                                            VStack(alignment: .leading) {
                                                Image(systemName: "gear")
                                                    .imageScale(.large)
                                                    .padding(.bottom, 10)
                                                Text("设置")
                                                    .font(.headline)
                                            }
                                            .foregroundColor(.white)
                                            Spacer()
                                        }
                                        .padding(.leading)
                                    }
                                    .frame(height: 120)
                                    .padding(.leading)
                                }
                                Button(action: {
                                    ClassName.IS_INTERNET_OPERATION_ALLOWED_FLAG = true
                                    presentation.wrappedValue.dismiss()
                                }) {
                                    Fluent_Rect {
                                        HStack {
                                            VStack(alignment: .leading) {
                                                Image(systemName: "chevron.left")
                                                    .padding(.bottom, 10)
                                                Text("返回班级列表")
                                                    .font(.headline)
                                            }
                                            .foregroundColor(.white)
                                            Spacer()
                                        }
                                        .padding(.leading)
                                    }
                                    .frame(height: 120)
                                    .padding(.trailing)
                                }
                            }
                            else {
                                HStack {
                                    Text("正在加载")
                                    Spacer()
                                    ProgressView()
                                        .progressViewStyle(CircularProgressViewStyle())
                                }.padding(.horizontal)
                            }
                        }
                        .navigationBarTitle("管理\(UserData.classNameStr)班")
                        Spacer()
                    }
                }
                .background(SUIAController(showAlert: $showError, $UIAController))
                
            }
//            if UserData.FILE_PROVIDER_IS_UPLOADING_FLAG {
//                Rectangle()
//                    .foregroundColor(_Color == .dark ? .black:.white)
//                    .overlay(
//                        VStack {
//                            ProgressView()
//                                .progressViewStyle(CircularProgressViewStyle())
//                                .frame(width: 120, height: 120)
//                            Text("正在应用更改")
//                                .font(.headline)
//                        }
//                    )
//                    .ignoresSafeArea()
//            }
        }
        .navigationViewStyle(StackNavigationViewStyle())
        .navigationBarHidden(true)
        .onReceive(timer) { _ in
            print("Receive at \(Date())")
            if !allowUpdate {
                return
            }
            if !UserData.FILE_DOWNLOAD_ISNOT_FINISHED_FLAG
            {
                allowUpdate = false
                connect()
            }
            //                    // print(UserData.FILE_DOWNLOAD_ISNOT_FINISHED_FLAG)
            withAnimation(.spring()) {
                self.showWarning = UserData.FILE_PROVIDER_IS_UPLOADING_FLAG
            }
            if !UserData.FILE_DOWNLOAD_ISNOT_FINISHED_FLAG {
                if let error = UserData.fileProviderError {
                    UserData.fileProviderError = nil
                    self.timer = Timer.TimerPublisher(interval: 120, runLoop: .current,
                                                      mode: .default).autoconnect()
                    let error = error as NSError
                    // print("errorCode: \(error.code)\n----------\n")
                    self.errorStr = error.localizedDescription + "\nPlease reopen the app or contact with your adiministrator for further help."
                    UIAController = UIAlertController(title: "网络错误", message: errorStr, preferredStyle: .alert)
                    UIAController.addAction(UIAlertAction(title: "取消", style: .cancel))
                    UIAController.addAction(UIAlertAction(title: "重试", style: .destructive, handler: { _ in
                        self.timer = Timer.TimerPublisher(interval: 5, runLoop: .current,
                                                          mode: .default).autoconnect()
                    }))
                    self.showError = true
                }
            }
        }
    }
    private func connect() {
            if UserData.downloadDataByHttp(stateCode: nil) {}
            else {
                if let error = UserData.fileProviderError {
                    UserData.fileProviderError = nil
                    self.errorStr = error.localizedDescription
//                    self.showError = true
                    allowUpdate = true
                }
            }
    }
}
